import 'dart:ui';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_book_store/home_model.dart';
import 'package:flutter_book_store/net/apis.dart';
import 'package:flutter_book_store/net/mock_adapter.dart';
import 'package:flutter_book_store/routes/app_pages.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';

class LoginWidget extends GetView {
  Map<String, dynamic> data = Map();
  var nameKey = 'NAME_KEY';
  var passKey = 'PASS_KEY';
SharedPreferences sp;
  void _getSp() async{
    sp=await SharedPreferences.getInstance();
  }
  @override
  Widget build(BuildContext context) {

  final HomeModel  _homeModel = Get.find();
    return Scaffold(
      body: SingleChildScrollView(
        child: Column(
          children: [
            Image.asset('images/loginImg.png'),
            SizedBox(height: 15),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              child: Column(
                children: [
                  InputText(
                    space: 33,
                    data: data,
                    dataKey: nameKey,
                    title: '用户名',
                    hintText: '请输入用户名',
                    obscureText: false,
                  ),
                  InputText(
                    space: 48,
                    obscureText: true,
                    data: data,
                    dataKey: passKey,
                    title: '密码',
                    hintText: '请输入密码',
                  ),
                  SizedBox(
                    height: 16,
                  ),
                  Column(
                    children: [
                      RoundButton(
                        onPressed: () {
                          final dio=Dio();
                          dio.httpClientAdapter = MockAdapter();
                          final api = RestClient(dio, baseUrl: MockAdapter.mockBase);
                          api.toLogin(data[nameKey],data[passKey]).then((value){
                            print(value);
                            if(value.status==1000){
                              _homeModel.name.value=value.data.username;
                              _homeModel.nickName.value=value.data.nickName;
                              _homeModel.jobNumber.value=value.data.jobNumber;
                              Get.back();
                              Get.snackbar('登录成功', '登录成功');
                            }else{
                              Get.snackbar('', '用户名或密码错误');
                            }
                          });
                        },
                        title: '登录',
                        color: Colors.green,
                      ),
                      SizedBox(
                        height: 16,
                      ),
                      Row(
                        mainAxisSize: MainAxisSize.max,
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          GestureDetector(
                              onTap: () {
                                Get.toNamed(Routes.REGISTER);
                                // FlutterBoost.singleton.open("sample://nativePage",
                                //     urlParams: <String, dynamic>{
                                //       "query": {"aaa": "bbb"}
                                //     });
                              },
                              child: Text(
                                '新用户注册',
                                style:
                                    TextStyle(color: Colors.blue, fontSize: 16),
                              ))
                        ],
                      )
                    ],
                  ),
                ],
              ),
            )
          ],
        ),
      ),
      appBar: AppBar(
        elevation: 0,
        leading: IconButton(
          onPressed: () {
            Get.back();
          },
          icon: Icon(
            Icons.arrow_back_ios,
            color: Colors.blue,
          ),
        ),
        centerTitle: true,
        backgroundColor: Colors.white,
        title: Text('用户登录',
            style: TextStyle(
                color: Colors.black,
                fontSize: 20,
                fontWeight: FontWeight.bold)),
      ),
    );
  }
}

class RoundButton extends StatelessWidget {
  final title;
  final color;
  final onPressed;

  const RoundButton({Key key, this.title, this.color, this.onPressed})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialButton(
      minWidth: double.infinity,
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.all(Radius.circular(16))),
      child: Text(
        title,
        style: TextStyle(color: Colors.white, fontSize: 16),
      ),
      color: color,
      onPressed: onPressed,
    );
  }
}

class InputText extends StatelessWidget {
  final title;
  final hintText;
  final data;
  final dataKey;
  final obscureText;
  final double space;

  const InputText(
      {Key key,
      this.title,
      this.hintText,
      this.data,
      this.dataKey,
      this.obscureText,
      this.space})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Row(
          children: [
            Text(
              title,
              style: TextStyle(color: Colors.black, fontSize: 16),
            ),
            SizedBox(
              width: space == null ? 0 : space,
            ),
            Expanded(
                child: ClearTextField(
              dataKey: dataKey,
              data: data,
              hintText: hintText,
              isPassword: obscureText,
            )),
          ],
        ),
        Container(
          height: 1,
          color: Colors.grey.shade300,
          width: double.infinity,
        )
      ],
    );
  }
}

class ClearTextField extends StatefulWidget {
  final String hintText;
  final isPassword;
  final data;
  final dataKey;

  const ClearTextField(
      {Key key, this.hintText, this.isPassword, this.data, this.dataKey})
      : super(key: key);

  @override
  _ClearTextFieldState createState() {
    return _ClearTextFieldState();
  }
}

class _ClearTextFieldState extends State<ClearTextField> {
  String _inputText = "";
  bool _hasDeleteIcon = false;
  bool _hasFocus = false;

  ///输入框焦点控制
  FocusNode _focusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    _focusNode.addListener(_focusNodeListener);
  }

  Future<Null> _focusNodeListener() async {
    if (_focusNode.hasFocus) {
      setState(() {
        _hasFocus = true;
      });
    } else {
      setState(() {
        _hasFocus = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    TextEditingController _controller = TextEditingController.fromValue(
        TextEditingValue(
            text: _inputText,
            selection: TextSelection.fromPosition(TextPosition(
                affinity: TextAffinity.downstream,
                offset: _inputText.length))));
    return TextField(
      focusNode: _focusNode,
      controller: _controller,
      inputFormatters: [
        FilteringTextInputFormatter.allow(RegExp(r'[a-zA-Z]|[0-9]')),
      ],
      decoration: InputDecoration(
        hintText: widget.hintText,
        hintStyle: TextStyle(color: Colors.grey, fontSize: 16),
        border: InputBorder.none,
        focusedBorder: InputBorder.none,
        suffixIcon: _hasDeleteIcon && _hasFocus
            ? IconButton(
                alignment: Alignment.center,
                padding: EdgeInsets.all(0.0),
                iconSize: 20,
                icon: Icon(Icons.cancel),
                onPressed: () {
                  setState(() {
                    _inputText = "";
                    _hasDeleteIcon = _inputText.isNotEmpty;
                  });
                },
              )
            : null,
      ),
      onChanged: (str) {
        widget.data[widget.dataKey] = str;
        setState(() {
          _inputText = str;
          _hasDeleteIcon = _inputText.isNotEmpty;
        });
      },
      onSubmitted: (str) {
        setState(() {
          _hasFocus = false;
        });
      },
      maxLines: 1,
      style: TextStyle(
          color: Colors.black,
          fontSize: 16,
          textBaseline: TextBaseline.alphabetic),
      obscureText: widget.isPassword,
    );
  }
}
